package com.sdry.web.controller.llm;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sdry.utils.ExcelUtils;
import com.sdry.utils.ResponseUtil;

import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import com.sdry.model.llm.DispatchBill;
import com.sdry.model.llm.DispatchBillDetail;
import com.sdry.model.llm.ProductPlanDetail;
import com.sdry.model.llm.ProductionPlan;
import com.sdry.model.llm.Replenish;
import com.sdry.model.llm.ReplenishDetail;
import com.sdry.model.llm.StorageArea;
import com.sdry.model.lz.Customer;
import com.sdry.model.lz.Materiel;
import com.sdry.model.lz.Warehouse;
import com.sdry.model.newAdd.Product;
import com.sdry.model.zc.ZcSysUserEntity;
import com.sdry.service.llm.DispatchBillDetailService;
import com.sdry.service.llm.DispatchBillService;
import com.sdry.service.llm.ProductPlanDetailService;
import com.sdry.service.llm.ProductionPlanService;
import com.sdry.service.llm.ReplenishDetailService;
import com.sdry.service.llm.ReplenishService;
import com.sdry.service.llm.StorageAreaService;
import com.sdry.service.lz.MaterielService;
import com.sdry.service.lz.StockOutOrderService;
import com.sdry.service.lz.WarehouseService;
import com.sdry.service.newAdd.ProductService;
/**
 *
 *@ClassName: ProductionPlanController
 *@Description: 生产计划
 *@Author llm
 *@Date 2019-07-02 17:32:04
 *@version 1.0
*/
@Controller
@RequestMapping("/ProductionPlanManager")
public class ProductionPlanController{
	@Resource ProductionPlanService productionPlanService;
	@Resource ProductPlanDetailService productPlanDetailService;
	@Resource ProductService productService;
	@Resource WarehouseService warehouseService;
	@Resource StockOutOrderService stockOutOrderService;
	@Resource StorageAreaService storageAreaService;
	@Resource MaterielService materielService;
	@Resource DispatchBillService dispatchBillService;
	@Resource DispatchBillDetailService dispatchBillDetailService;
	@Resource ReplenishService replenishService;
	@Resource ReplenishDetailService replenishDetailService;
	/** 
	 * 进入页面
	 * @param model
	 * @return 页面路径
	*/
	@RequestMapping("/page")
	public ModelAndView pageProductionPlan (Model model) {
		ModelAndView mav = new ModelAndView();
		List<Warehouse> allWarehouse = warehouseService.queryAllWarehouse();
		mav.addObject("allWarehouse", allWarehouse);
		List<Customer> allSupplier = stockOutOrderService.queryAllCustomerByType();
		mav.addObject("allSupplier", allSupplier);
		List<Customer> allClient = stockOutOrderService.queryAllCustomerByType1();
		mav.addObject("allClient", allClient);
		mav.setViewName("/llm/productionPlan");
		return mav;
	}
	/** 
	 * 根据主键id查询实体
	 * @param id 主键id
	 * @return 实体
	*/
	@RequestMapping("/queryById")
	@ResponseBody
	public ProductionPlan queryById(Long id) {
		ProductionPlan param = productionPlanService.queryById(id);
		return param;
	}
	/** 
	 * 条件查询所有
	 * @param param 实体条件
	 * @return 实体集合
	*/
	@RequestMapping("/queryAllByMution")
	@ResponseBody
	public List<ProductionPlan> queryAllByMution(ProductionPlan param) {
		List<ProductionPlan> list = productionPlanService.queryAllByMution(param);
		return list;
	}
	/** 
	 * 条件分页查询
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/list")
	public void list(ProductionPlan param, HttpServletResponse response) throws Exception{
		/*
		 * 条件分页查询内容
		 */
		List<ProductionPlan> list = productionPlanService.findPageByMution(param);
		/*
		 * 条件查询总条数
		 */
		Integer total = productionPlanService.selectCountByMution(param);
		/*
		 * 转为json数据传至页面
		 */
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", total);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/** 
	 * 插入返回id
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/insert")
	public void insert(ProductionPlan param, HttpServletResponse response) throws Exception{
		Long id = productionPlanService.insert(param);
		response.getWriter().print(id);
	}
	/** 
	 * 根据主键更新 返回影响行数
	 * @param param 实体条件
	 * @param response
	 * @throws Exception
	*/
	@RequestMapping("/update")
	public void update(ProductionPlan param,HttpServletResponse response) throws Exception{
		Integer count = productionPlanService.update(param);
		response.getWriter().print(count);
	}
	/** 
	 * 根据主键拼接的字符串删除返回影响行数
	 * @param ids 主键拼接的字符串
	 * @return 影响行数
	*/
	@RequestMapping("/delete")
	public void delete(String ids,HttpServletResponse response) throws Exception{
		ids=ids.replace("'",""); 
		Integer count = productionPlanService.delete(ids);
		response.getWriter().print(count);
	}
	/**
	 * 上传生产计划
	 * @param file	上传的文件
	 * @param response
	 */
	@RequestMapping(value="/uploadProductionPlan", method = RequestMethod.POST)
    @ResponseBody
	public Map<String, Object> uploadProductionPlan(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> map = new HashMap<>();
	    String desFilePath = "";
		// 1.获取原文件名1
        String newName = file.getOriginalFilename();
		// 2.获取要保存的路径文件夹1
		String realPath = request.getSession().getServletContext().getRealPath("/uploadFile/");
		// 3.保存
		desFilePath = realPath + "\\" + newName;
		File desFile = new File(desFilePath);
		try {
			file.transferTo(desFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
		map.put("fileName",newName);
		map.put("isSuccess",1);
		return  map;
	}
	
	/**
     * 把生产计划存入数据库
     * @param param
     * @param response
     * @return
     */
    @RequestMapping("/importProductionPlan")
    public void importProductionPlan(ProductionPlan param, HttpServletRequest request, HttpServletResponse response){
        String fileName = param.getFileName();
        String savePath = request.getSession().getServletContext().getRealPath("/uploadFile/"+fileName);
        //取文件后缀
        String subfix = fileName.lastIndexOf(".")==-1? "" : fileName.substring(fileName.lastIndexOf(".")+1);
        List<List<String>> lists = new ArrayList<>();
        //获取导入列数
        int num = 5;
        try {
            //用工具类读取导入的文件
            if(subfix.equals("xls")){
                lists = ExcelUtils.readXls(savePath, request, num);
            }else if(subfix.equals("xlsx")){
                    lists = ExcelUtils.readXlsx(savePath, request, num);
            }else{
                    response.getWriter().print("0");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        int flag = 1;
        ProductionPlan plan = new ProductionPlan();
		ProductPlanDetail planDetail = new ProductPlanDetail();
		Product product = new Product();
        Long affact = 0L;
        Long detailId = 0L;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //获取每一行要导入的数据，第一列为生产计划单号，第二列为计划生产日期，第三列为产品名称，第四列为产品编号，第五列为产品数量
        for (int i = 0; i < lists.size(); i++) {
            List<String> list = new ArrayList<>();
            list= lists.get(i);
            plan.setSupplier_id(param.getSupplier_id());
            plan.setClient_id(param.getClient_id());
            plan.setWarehouse_id(param.getWarehouse_id());
            plan.setStatus1(0+"");
            plan.setStatus2(0+"");
            plan.setPlan_number(list.get(0));   //第一列
            plan.setStart_date(list.get(1));    //第二列
            ZcSysUserEntity user = (ZcSysUserEntity)request.getSession().getAttribute("user");
            plan.setUser_id(user.getId());
            plan.setCreate_date(sdf.format(new Date()));
            //保存生产计划
            affact = productionPlanService.insert(plan);
            if(affact > 0) {
                //获取返回排产单id
                planDetail.setPlanId(affact);
                /**
                 * 重复开始的地方
                 * 如果一个计划单有多个产品，就需要把这行的每三列作为一条详情记录存入数据库，存入多次
                 * 例如：这个计划单有两个产品，3、4、5列存入详情，6、7、8列存入详情，要存入两次
                 * 注：一个list集合是一行，下标是从0开始，所以第三列，下标为2，即list.get(2)
                 */
                planDetail.setProductQuantity(Integer.parseInt(list.get(4)));   //第五列
				//根据产品名称，编号，查询ID，存入计划详情
				product.setProductName(list.get(2));	
				product.setProductNumber(list.get(3));
				Long productId = productService.queryIdByMution(product);
				if(productId > 0){
					planDetail.setProductId(productId);
	                //添加生产计划详情
	                detailId = productPlanDetailService.insert(planDetail);
	                /**
	                 * 结束重复的地方
	                 */
	                if(detailId <= 0){
	                	//如果详情添加失败，删除已添加的生产计划
	                    productionPlanService.delete(affact.toString());
	                    flag = 0;
	                    break;
	                }
				}else{
					//如果详情添加失败，删除已添加的生产计划
                    productionPlanService.delete(affact.toString());
                    flag = -1;
                    break;
				}
            }
        }
        try {
            response.getWriter().print(flag);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 根据生产计划生成发货单  
     * @param id	主键ID
     * @param response	
     */
    @RequestMapping("/createShipmentsTask")
    public void createShipmentsTask(Long id, HttpServletRequest request, HttpServletResponse response){
    	//1、根据计划单ID查所有产品（集合）
    	//2、根据产品找到对应的bom（遍历产品集合，生成物料集合）
    	//3、遍历物料集合
    	//3.1、用计划数量-库存数量=发货数量，存入物料集合
    	//3.2、查供应商ID存入新的供应商集合，存入物料集合（供应商ID存入两个集合）
    	//4、把供应商集合转为set集合，以去重，又把set转为新的供应商集合
    	//5、遍历供应商集合，在内部遍历物料集合，如果供应商ID与物料集合的供应商ID一样，供应商ID存入发货单，物料ID，数量存入发货单详情
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	ZcSysUserEntity user = (ZcSysUserEntity)request.getSession().getAttribute("user");
    	ProductionPlan plan = productionPlanService.queryById(id);
    	List<ProductPlanDetail> productList = new ArrayList<>();
    	//第一步、获取计划单所有产品，存入集合：productList
    	ProductPlanDetail pd = new ProductPlanDetail();
		pd.setPlanId(id);
		List<ProductPlanDetail> list1 = productPlanDetailService.queryAllByMution(pd);
		for(ProductPlanDetail p : list1){
			productList.add(p);
		}
    	//第二步、根据 bom，获取所有物料，存入集合：materielList
    	List<DispatchBillDetail> materielList = new ArrayList<>();
    	for(ProductPlanDetail pro : productList){
    		List<DispatchBillDetail> dlist1 = productionPlanService.findMaterielByProductBom(pro.getProductId());
    		for(DispatchBillDetail d : dlist1){
    			d.setMaterielQuantity(d.getMaterielQuantity() * pro.getProductQuantity());
    			materielList.add(d);
    		}
    	}
    	//第三步、bom合并，把相同的物料Id进行累加
    	//3.1、相同的物料求和
    	for(int i = 0; i < materielList.size(); i ++){
    		int bomSum = 0;
    		for(int a = 0; a < materielList.size(); a ++){
    			if(materielList.get(i).getMaterielId() == materielList.get(a).getMaterielId()){
    				bomSum  +=  materielList.get(a).getMaterielQuantity();
    			}
    		}
    		materielList.get(i).setMaterielQuantity(bomSum);
    	}
    	//3.2、相同的物料去重
    	Set<DispatchBillDetail> set = new TreeSet<DispatchBillDetail>(new Comparator<DispatchBillDetail>() {
            @Override
            public int compare(DispatchBillDetail o1, DispatchBillDetail o2) {
                //字符串,则按照asicc码升序排列
                return o1.getMaterielId().compareTo(o2.getMaterielId());
            }
        });
        set.addAll(materielList);
        List<DispatchBillDetail> bomList = new ArrayList<>(set);
        //第四步、遍历物料集合，查询线边库存，计算发货数量
        Set<Long> supplierSet = new HashSet<>();
        StorageArea sa = new StorageArea();
        for(DispatchBillDetail ma : bomList){
        	sa.setMaterielId(ma.getMaterielId());
        	List<StorageArea> li = storageAreaService.findPageByMution(sa);
        	if(li.size() > 0){
        		ma.setStorageQuantity(li.get(0).getSumQuantity());
        	}else{
        		ma.setStorageQuantity(0);
        	}
        	//发货数量 = 计划数量 - 线边库存数量
        	ma.setShipmentsQuantity(ma.getMaterielQuantity() - ma.getStorageQuantity());
        	ma.setPlanQuantity(ma.getMaterielQuantity());
        	//根据物料ID查供应商
        	Materiel materiel = materielService.queryMaterielById(ma.getMaterielId());
        	ma.setSupplierId(materiel.getCustomer_id());
        	supplierSet.add(materiel.getCustomer_id());
        }
        //第五步、根据不同的供应商生成多个发货单
        int flag = 1;
        DispatchBill dispatchBill = new DispatchBill();
        start:for(Long supplierId : supplierSet){
        	dispatchBill.setUser_id(user.getId());
        	dispatchBill.setCreate_date(sdf.format(new Date()));
        	dispatchBill.setClient_id(plan.getClient_id());
        	dispatchBill.setWarehouse_id(plan.getWarehouse_id());
        	dispatchBill.setSupplier_id(supplierId);
        	dispatchBill.setPlan_id(id);
        	dispatchBill.setStatus(0+"");
        	//保存计划单
        	Long affct = dispatchBillService.insert(dispatchBill);
        	if(affct > 0){
        		for(DispatchBillDetail ma : bomList){
            		if(supplierId == ma.getSupplierId()){
            			ma.setDispatchId(affct);
            			//保存计划单详情
            			Long detailId = dispatchBillDetailService.insert(ma);
            			if(detailId < 0){
            				flag = 0;
            				break start;
            			}
            		}
            	}
        	}else{
        		flag = 0;
				break;
        	}
        }
        plan.setStatus1(1+"");
        productionPlanService.update(plan);
        try {
			ResponseUtil.write(response, flag);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    /**
     * 根据生产计划生成补货计划  
     * @param id	主键ID
     * @param response	
     */
    /*@RequestMapping("/createDemandTask")
    public void createDemandTask(Long id, HttpServletRequest request, HttpServletResponse response){
    	//1、根据计划单ID查所有产品（集合）
    	//2、根据产品找到对应的bom（遍历产品集合，生成物料集合）
    	//3、遍历物料集合
    	//3.1、用计划数量-库存数量=发货数量，存入物料集合
    	//3.2、查供应商ID存入新的供应商集合，存入物料集合（供应商ID存入两个集合）
    	//4、把供应商集合转为set集合，以去重，又把set转为新的供应商集合
    	//5、遍历供应商集合，在内部遍历物料集合，如果供应商ID与物料集合的供应商ID一样，供应商ID存入发货单，物料ID，数量存入发货单详情
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	ZcSysUserEntity user = (ZcSysUserEntity)request.getSession().getAttribute("user");
    	ProductionPlan plan = productionPlanService.queryById(id);
    	List<ProductPlanDetail> productList = new ArrayList<>();
    	//第一步、获取计划单所有产品，存入集合：productList
    	ProductPlanDetail pd = new ProductPlanDetail();
		pd.setPlanId(id);
		List<ProductPlanDetail> list1 = productPlanDetailService.queryAllByMution(pd);
		for(ProductPlanDetail p : list1){
			productList.add(p);
		}
    	//第二步、根据 bom，获取所有物料，存入集合：materielList
    	List<DispatchBillDetail> materielList = new ArrayList<>();
    	for(ProductPlanDetail pro : productList){
    		List<DispatchBillDetail> dlist1 = productionPlanService.findMaterielByProductBom(pro.getProductId());
    		for(DispatchBillDetail d : dlist1){
    			d.setMaterielQuantity(d.getMaterielQuantity() * pro.getProductQuantity());
    			materielList.add(d);
    		}
    	}
    	//第三步、bom合并，把相同的物料Id进行累加
    	//3.1、相同的物料求和
    	for(int i = 0; i < materielList.size(); i ++){
    		int bomSum = 0;
    		for(int a = 0; a < materielList.size(); a ++){
    			if(materielList.get(i).getMaterielId() == materielList.get(a).getMaterielId()){
    				bomSum  +=  materielList.get(a).getMaterielQuantity();
    			}
    		}
    		materielList.get(i).setMaterielQuantity(bomSum);
    	}
    	//3.2、相同的物料去重
    	Set<DispatchBillDetail> set = new TreeSet<DispatchBillDetail>(new Comparator<DispatchBillDetail>() {
            @Override
            public int compare(DispatchBillDetail o1, DispatchBillDetail o2) {
                //字符串,则按照asicc码升序排列
                return o1.getMaterielId().compareTo(o2.getMaterielId());
            }
        });
        set.addAll(materielList);
        List<DispatchBillDetail> bomList = new ArrayList<>(set);
        //第四步、遍历物料集合，查询线边库存，计算发货数量
        Set<Long> supplierSet = new HashSet<>();
        for(DispatchBillDetail ma : bomList){
        	//查库存数量
        	Integer mNum = productionPlanService.getInventoryByMaterielId(ma.getMaterielId());
        	if(mNum != null){
        		ma.setStorageQuantity(mNum);
        	}else{
        		ma.setStorageQuantity(0);
        	}
        	//发货数量 = 计划数量 - 线边库存数量
        	ma.setShipmentsQuantity(ma.getMaterielQuantity() - ma.getStorageQuantity());
        	ma.setPlanQuantity(ma.getMaterielQuantity());
        	//根据物料ID查供应商
        	Materiel materiel = materielService.queryMaterielById(ma.getMaterielId());
        	ma.setSupplierId(materiel.getCustomer_id());
        	supplierSet.add(materiel.getCustomer_id());
        }
        //第五步、根据不同的供应商生成多个发货单
        int flag = 1;
        Replenish replenish = new Replenish();
        ReplenishDetail replenishDetail = new ReplenishDetail();
        start:for(Long supplierId : supplierSet){
        	replenish.setUser_id(user.getId());
        	replenish.setCreate_date(sdf.format(new Date()));
        	replenish.setClient_id(plan.getClient_id());
        	replenish.setWarehouse_id(plan.getWarehouse_id());
        	replenish.setSupplier_id(supplierId);
        	replenish.setPlan_id(id);
        	replenish.setStatus(0+"");
        	//保存计划单
        	Long affct = replenishService.insert(replenish);
        	if(affct > 0){
        		for(DispatchBillDetail ma : bomList){
            		if(supplierId == ma.getSupplierId()){
            			replenishDetail.setReplenish_id(affct);
            			replenishDetail.setMateriel_id(ma.getMaterielId());
            			replenishDetail.setActual_stock(ma.getStorageQuantity());
            			replenishDetail.setDemand_quantity(ma.getShipmentsQuantity());
            			replenishDetail.setSafe_stock(ma.getMaterielQuantity());
            			//保存计划单详情
            			Long detailId = replenishDetailService.insert(replenishDetail);
            			if(detailId < 0){
            				flag = 0;
            				break start;
            			}
            		}
            	}
        	}else{
        		flag = 0;
				break;
        	}
        }
        plan.setStatus2(1+"");
        productionPlanService.update(plan);
        try {
			ResponseUtil.write(response, flag);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }*/
    
    /**
     * 根据生产计划生成补货计划  
     * @param id	主键ID
     * @param response	
     */
    @RequestMapping("/createDemandTask")
    public void createDemandTask(Long id, HttpServletRequest request, HttpServletResponse response){
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	ZcSysUserEntity user = (ZcSysUserEntity)request.getSession().getAttribute("user");
    	ProductionPlan plan = productionPlanService.queryById(id);
    	List<ProductPlanDetail> productList = new ArrayList<>();
    	//第一步、获取计划单所有产品，存入集合：productList
    	ProductPlanDetail pd = new ProductPlanDetail();
		pd.setPlanId(id);
		List<ProductPlanDetail> list1 = productPlanDetailService.queryAllByMution(pd);
		for(ProductPlanDetail p : list1){
			productList.add(p);
		}
    	//第二步、根据 bom，获取所有物料，存入集合：materielList
    	List<DispatchBillDetail> materielList = new ArrayList<>();
    	for(ProductPlanDetail pro : productList){
    		List<DispatchBillDetail> dlist1 = productionPlanService.findMaterielByProductBom(pro.getProductId());
    		for(DispatchBillDetail d : dlist1){
    			d.setMaterielQuantity(d.getMaterielQuantity() * pro.getProductQuantity());
    			materielList.add(d);
    		}
    	}
    	//第三步、对bom集合进行去重
    	Set<DispatchBillDetail> set = new TreeSet<DispatchBillDetail>(new Comparator<DispatchBillDetail>() {
            @Override
            public int compare(DispatchBillDetail o1, DispatchBillDetail o2) {
                //字符串,则按照asicc码升序排列
                return o1.getMaterielId().compareTo(o2.getMaterielId());
            }
        });
        set.addAll(materielList);
        List<DispatchBillDetail> bomList = new ArrayList<>(set);
        //第四步、遍历集合，根据物料ID查仓库安全库存和现有实际库存
        Set<Long> supplierSet = new HashSet<>();
        for(DispatchBillDetail ma : bomList){
        	Long materielId = ma.getMaterielId();
        	//查安全库存
        	Materiel m = materielService.queryMaterielById(materielId);
        	ma.setPlanQuantity(m.getLower_value());
        	//查实际库存
        	//查库存数量
        	Integer mNum = productionPlanService.getInventoryByMaterielId(ma.getMaterielId());
        	if(mNum != null){
        		ma.setStorageQuantity(mNum);
        	}else{
        		ma.setStorageQuantity(0);
        	}
        	ma.setShipmentsQuantity(ma.getPlanQuantity() - ma.getStorageQuantity());
        	//根据物料ID查供应商
        	Materiel materiel = materielService.queryMaterielById(ma.getMaterielId());
        	ma.setSupplierId(materiel.getCustomer_id());
        	supplierSet.add(materiel.getCustomer_id());
        }
        //第五步、根据不同的供应商生成多个发货单
        int flag = 1;
        Replenish replenish = new Replenish();
        ReplenishDetail replenishDetail = new ReplenishDetail();
        start:for(Long supplierId : supplierSet){
        	replenish.setUser_id(user.getId());
        	replenish.setCreate_date(sdf.format(new Date()));
        	replenish.setClient_id(plan.getClient_id());
        	replenish.setWarehouse_id(plan.getWarehouse_id());
        	replenish.setSupplier_id(supplierId);
        	replenish.setPlan_id(id);
        	replenish.setStatus(0+"");
        	//保存计划单
        	Long affct = replenishService.insert(replenish);
        	if(affct > 0){
        		for(DispatchBillDetail ma : bomList){
            		if(supplierId == ma.getSupplierId()){
            			replenishDetail.setReplenish_id(affct);
            			replenishDetail.setMateriel_id(ma.getMaterielId());
            			replenishDetail.setActual_stock(ma.getStorageQuantity());
            			replenishDetail.setDemand_quantity(ma.getShipmentsQuantity());
            			replenishDetail.setSafe_stock(ma.getPlanQuantity());
            			//保存计划单详情
            			Long detailId = replenishDetailService.insert(replenishDetail);
            			if(detailId < 0){
            				flag = 0;
            				break start;
            			}
            		}
            	}
        	}else{
        		flag = -1;
				break;
        	}
        }
        plan.setStatus2(1+"");
        productionPlanService.update(plan);
        try {
			ResponseUtil.write(response, flag);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
}
